package org.testtools.runner.impl;

import org.testtools.runner.LoopRunnable;

public class LoopRunner {

    private static final int NANO_TO_MILLIS = 1000 * 1000;

    private long initTime = System.nanoTime();
    private int rate;
    private int timeout;
    private Object result = null;

    public LoopRunner(int timeout, int rate) {
        this.rate = rate;
        this.timeout = timeout;
    }

    public Object run(LoopRunnable runner) {
        while (true) {
            synchronized (this) {
                if (((System.nanoTime() - initTime) / NANO_TO_MILLIS) > timeout)
                    break;
            }

            if ((result = execute(runner)) != null)
                break;

            try {
                Thread.sleep(rate);
            } catch (InterruptedException ioe) {
            }
        }

        return result;
    }

    private Object execute(LoopRunnable runner) {
        runner.run();
        return runner.getResult();
    }
}